package cn.dark.auth.core.spring;

import cn.dark.auth.core.repository.LoginRepository;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ServiceLoaderUtil;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author dark
 * @date 2023-10-25
 */
@Slf4j
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory)
        throws BeansException {
        List<LoginRepository> loginRepositories = ServiceLoaderUtil.loadList(LoginRepository.class);
        if (CollUtil.isEmpty(loginRepositories)) {
            throw new RuntimeException("未加载到登录仓储服务对象");
        }

        if (loginRepositories.size() > 1) {
            throw new RuntimeException("登录仓储服务对象实例不能大于1");
        }

        String name = LoginRepository.class.getName();
        LoginRepository repository = loginRepositories.get(0);
        configurableListableBeanFactory.registerSingleton(name, repository);
        log.info("加载登录仓储服务对象成功，beanName：{}，实际对象名称：{}", name, repository.getClass().getName());
    }
}
